"""_summary_
遍历存储在硬盘里的雷达数据
1. 
"""

import struct
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import argparse

FIELD_CONFG = {
    'head': {
        'len': 8,
        'offset': 0
    },
    'gps_week': {
        'len': 4,
        'offset': 8
    },
    'gps_second': {
        'len': 8,
        'offset': 12
    },
    'gps_sub_time': {
        'len': 4,
        'offset': 20
    },
    'azimuth': {
        'len': 8,
        'offset': 24
    },
    'pitch': {
        'len': 8,
        'offset': 32
    },
    'roll': {
        'len': 8,
        'offset': 40
    },
    'latitude': {
        'len': 8,
        'offset': 48
    },
    'longitude': {
        'len': 8,
        'offset': 56
    },
    'height': {
        'len': 8,
        'offset': 64
    },
    'motor_bits': {
        'len': 4,
        'offset': 72
    },
    'motor_cnt': {
        'len': 4,
        'offset': 76
    },
    'channal_num': {
        'len': 4,
        'offset': 80
    },
    'sys_info': {
        'len': 4,
        'offset': 84
    },
}

class ParseRadar:
    # 保存每次采集数据帧的起点位置
    samplePos = []
    firstPos = 0
    firstLen = 0
    secondPos = 0
    secondLen = 0

    fieldValue = []

    ch0FirstPeak = []
    ch0SecondPeak = []
    ch1SecondPeak = []
    ch2SecondPeak = []
    ch3SecondPeak = []
    filename = ""
    frame_head = b'\x01\x23\x45\x67\x89'
    ch0_head = b'\xeb\x90\xa5\x5a\x00\x00'
    ch1_head = b'\xeb\x90\xa5\x5a\x0f\x0f'
    ch2_head = b'\xeb\x90\xa5\x5a\xf0\xf0'
    ch3_head = b'\xeb\x90\xa5\x5a\xff\xff'
    readed_position = 0

    def __init__(self, name):
        self.filename = name

        """
        获得那种雷达存储的数据
        1. 找到帧头，根据偏移位置
        """
    def getType(self):
        pass 


    def read_in_chunks(self, f, chunk_size=512):
        while True:
            data = f.read(chunk_size)  # 每次读取指定的长度
            if not data:
                break
            yield data


    """
    分析文件里有多少次采集数据
    """
    def getTotalSampleCount(self):
        with open(self.filename, 'rb') as f:
            chunk_size = 1024
            for chuck in self.read_in_chunks(f, chunk_size):
                head_pos = chuck.find(self.frame_head)
                if head_pos >= 0:  # 没有找到数据头
                    self.samplePos.append(self.readed_position + head_pos)

                self.readed_position += chunk_size

        return self.samplePos
    """
    获得第一段、第二段数据的起始位置和采集长度信息
    """
    def getParaInfo(self):
        f = open(self.filename, "rb")
        f.seek(self.samplePos[0])
        data = f.read(self.samplePos[1]-self.samplePos[0])
        f.close()
        head_pos = data.find(self.ch0_head)
        if head_pos > 0:
            offset = head_pos + 6
            target = data[offset :offset + 2]
            self.firstPos = int.from_bytes(target, byteorder='big')

            offset = head_pos + 8
            target = data[offset :offset + 2]
            self.firstLen = int.from_bytes(target, byteorder='big')
            return self.firstLen
        else:
            return -1

    def printInfo(self):
        print("Total sample count = {}\nEach frame length = {}".format(len(self.samplePos), self.samplePos[1]-self.samplePos[0]))
        print("First pos = {}".format(self.firstPos))
        print("First len = {}".format(self.firstLen))

    def getMotorCnt(self):
        pass


    def getChFirstPeak(self, data, head):
        pos = data.find(head)
        offset = pos + 8
        target = data[offset : offset + 2]
        self.firstLen = int.from_bytes(target, byteorder='big')

        offset = pos + 10
        first_data = data[offset : offset + self.firstLen * 2]\

        dt = np.dtype(np.uint16)
        dt = dt.newbyteorder('>')
        arr = np.frombuffer(first_data, dtype=dt)
        max_index = np.argmax(arr)
        return max_index+self.firstPos, first_data[max_index]

    def getChSecondPeak(self, data, head):
        pos = data.find(head)
        offset = pos + 8 + self.firstLen * 2 + 2
        target = data[offset: offset + 2]
        self.secondPos = int.from_bytes(target, byteorder='big')
        offset = pos + 10 + self.firstLen * 2 + 2
        target = data[offset: offset + 2]
        self.secondLen = int.from_bytes(target, byteorder='big')

        offset = pos + 10 + self.firstLen * 2 + 4
        second_data = data[offset : offset + self.secondLen * 2]

        dt = np.dtype(np.uint16)
        dt = dt.newbyteorder('>')
        arr = np.frombuffer(second_data, dtype=dt)
        max_index = np.argmax(arr)
        return max_index+self.secondPos, second_data[max_index]
    """
    获得所有通道第一段数据的峰值点的位置
    """
    def getPeak(self):
        f = open(self.filename, "rb")
        length = self.samplePos[1]-self.samplePos[0]
        for pos in self.samplePos:
            f.seek(pos)
            data = f.read(length)  # data是完整的采集数据帧
            idx, value = self.getChFirstPeak(data, self.ch0_head)
            self.ch0FirstPeak.append(idx)
            idx, value = self.getChSecondPeak(data, self.ch0_head)
            self.ch0SecondPeak.append(idx)
            idx, value = self.getChSecondPeak(data, self.ch1_head)
            self.ch1SecondPeak.append(idx)
            idx, value = self.getChSecondPeak(data, self.ch2_head)
            self.ch2SecondPeak.append(idx)
            idx, value = self.getChSecondPeak(data, self.ch3_head)
            self.ch3SecondPeak.append(idx)


        return self.ch0FirstPeak, self.ch0SecondPeak, self.ch1SecondPeak, self.ch2SecondPeak, self.ch3SecondPeak

    """
    从数据指定的位置，读取len长度的数据
    """
    def getValueAtOffset(self, offset, len):
        result = []
        f = open(self.filename, "rb")
        for pos in self.samplePos:
            f.seek(pos)
            data = f.read(88)  # data是完整的采集数据帧
            value = data[offset: offset + len]
            value = int.from_bytes(value, byteorder='big')
            result.append(value)

        return result

    """
    分析文件里的前N次完整采集数据
    """
    def setAnalyzeNumbers(self, num):
        pass

if __name__ == '__main__':
    ch0FirstPeak, ch0SecondPeak, ch1SecondPeak, ch2SecondPeak, ch3SecondPeak = [], [], [], [], []
    parser = argparse.ArgumentParser(description="处理个数不定的参数")
    parser.add_argument("--file", help="Files to be parsed")

    # parser.add_argument("-c", "--command", type=str, help="select command to test")
    parser.add_argument("-p", "--plot", type=str, choices=['ch0FirstPeak', 'ch0SecondPeak', 'ch1SecondPeak'], nargs="*", help="select command to test")
    args = parser.parse_args()


    # parse = ParseRadar("/home/wj/Desktop/drone_2023_09_05_16_01_52.bin")
    # parse = ParseRadar("/home/wj/Desktop/2018_03_03_15_16_28_ocean_Addr_0052.bin")
    parse = ParseRadar(args.file)
    # parse = ParseRadar("/home/wj/Desktop/deepsea_2023_09_21_14_38_58.bin")
    parse.getTotalSampleCount()
    parse.getParaInfo()
    parse.printInfo()


    # ch0FirstPeak, ch0SecondPeak, ch1SecondPeak, ch2SecondPeak, ch3SecondPeak = parse.getPeak()
    scanMotor1 = parse.getValueAtOffset(72, 4)
    scanMotor2 = parse.getValueAtOffset(76, 4)

    df = pd.DataFrame({
        #               'ch0FirstPeak': ch0FirstPeak,
        #                'ch0SecondPeak': ch0SecondPeak,
        #                'ch1SecondPeak': ch1SecondPeak,
        #                'ch2SecondPeak': ch2SecondPeak,
        #                'ch3SecondPeak': ch3SecondPeak,
                       'scanMotor1': scanMotor1,
                       'scanMotor2': scanMotor2,
                       })



    fig, ax = plt.subplots(2, 1, sharex=True)
    ax[0].plot(df['scanMotor1'])
    ax[0].grid(True)
    ax[1].plot(df['scanMotor2'])
    ax[1].grid(True)
    plt.show()

    pass